<template>
  <div class="order-confirm-container">
    <div class="page-header">
      <h2>确认订单</h2>
    </div>

    <!-- 收货地址 -->
    <el-card class="section">
      <template #header>
        <div class="card-header">
          <span>收货地址</span>
          <el-button type="text" @click="showAddressDialog = true">新增/修改地址</el-button>
        </div>
      </template>
      
      <div v-if="selectedAddress" class="address-card" @click="showAddressDialog = true">
        <div class="address-info">
          <div class="address-header">
            <span class="name">{{ selectedAddress.name }}</span>
            <span class="phone">{{ selectedAddress.phone }}</span>
            <el-tag v-if="selectedAddress.isDefault" size="small" type="primary">默认</el-tag>
          </div>
          <div class="address-detail">
            {{ selectedAddress.province }} {{ selectedAddress.city }} {{ selectedAddress.district }} {{ selectedAddress.detailAddress }}
          </div>
        </div>
      </div>
      <div v-else class="empty-address" @click="showAddressDialog = true">
        <el-empty description="请添加收货地址">
          <template #image>
            <el-icon><i-ep-location /></el-icon>
          </template>
        </el-empty>
      </div>
    </el-card>

    <!-- 商品信息 -->
    <el-card class="section">
      <template #header>
        <div class="card-header">
          <span>商品信息</span>
        </div>
      </template>
      
      <el-table :data="checkoutItems" style="width: 100%">
        <el-table-column prop="id" label="商品ID" width="80" />
        <el-table-column label="商品信息" width="300">
          <template #default="scope">
            <div class="product-info">
              <img :src="scope.row.image" alt="商品图片" class="product-image">
              <div class="product-details">
                <div class="product-title">{{ scope.row.title }}</div>
                <div class="product-category">{{ scope.row.categoryName }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单价" width="120">
          <template #default="scope">
            <span class="price">¥{{ scope.row.price.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数量" width="100" prop="quantity" />
        <el-table-column label="小计" width="120">
          <template #default="scope">
            <span class="subtotal">¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 订单信息 -->
    <el-card class="section">
      <template #header>
        <div class="card-header">
          <span>订单信息</span>
        </div>
      </template>
      
      <div class="order-form">
        <el-form label-width="120px">
          <el-form-item label="支付方式">
            <el-radio-group v-model="paymentMethod">
              <el-radio label="wechat">微信支付</el-radio>
              <el-radio label="alipay">支付宝</el-radio>
              <el-radio label="cash">货到付款</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="订单备注">
            <el-input v-model="remark" type="textarea" :rows="2" placeholder="请输入备注信息"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 支付信息 -->
    <div class="payment-summary">
      <div class="summary-item">
        <span>商品总价：</span>
        <span>¥{{ subtotal.toFixed(2) }}</span>
      </div>
      <div class="summary-item">
        <span>运费：</span>
        <span>¥{{ shippingFee.toFixed(2) }}</span>
      </div>
      <div class="summary-item total">
        <span>实付金额：</span>
        <span class="total-price">¥{{ totalAmount.toFixed(2) }}</span>
      </div>
      
      <div class="submit-btn">
        <el-button type="primary" size="large" @click="submitOrder" :loading="isSubmitting">
          提交订单
        </el-button>
      </div>
    </div>

    <!-- 地址编辑弹窗 -->
    <el-dialog v-model="showAddressDialog" title="编辑收货地址" width="600px">
      <el-form :model="addressForm" :rules="addressRules" ref="addressFormRef" label-width="100px">
        <el-form-item label="收货人" prop="name">
          <el-input v-model="addressForm.name" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="所在地区" prop="region">
          <el-cascader
            v-model="addressForm.region"
            :options="regionOptions"
            placeholder="请选择省市区"
            change-on-select
          ></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input
            v-model="addressForm.detailAddress"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddressDialog = false">取消</el-button>
          <el-button type="primary" @click="saveAddress">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useCartStore, useOrderStore } from '../../store'

const router = useRouter()
const cartStore = useCartStore()
const orderStore = useOrderStore()

// 从sessionStorage获取结算商品
const checkoutItems = ref([])
const isSubmitting = ref(false)
const showAddressDialog = ref(false)
const addressFormRef = ref(null)

// 支付方式和备注
const paymentMethod = ref('wechat')
const remark = ref('')

// 地址表单
const addressForm = reactive({
  name: '',
  phone: '',
  region: [],
  detailAddress: '',
  isDefault: false
})

// 地址验证规则
const addressRules = {
  name: [{ required: true, message: '请输入收货人姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  region: [{ required: true, message: '请选择所在地区', trigger: 'change' }],
  detailAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
}

// 区域选项（模拟数据）
const regionOptions = ref([
  { value: '北京市', label: '北京市', children: [
    { value: '北京市', label: '北京市', children: [
      { value: '朝阳区', label: '朝阳区' },
      { value: '海淀区', label: '海淀区' },
      { value: '西城区', label: '西城区' }
    ]}
  ]},
  { value: '上海市', label: '上海市', children: [
    { value: '上海市', label: '上海市', children: [
      { value: '浦东新区', label: '浦东新区' },
      { value: '静安区', label: '静安区' }
    ]}
  ]}
])

// 选中的地址
const selectedAddress = ref(null)

onMounted(() => {
  // 获取结算商品
  const storedItems = sessionStorage.getItem('checkoutItems')
  if (storedItems) {
    checkoutItems.value = JSON.parse(storedItems)
  } else {
    ElMessage.warning('没有找到要结算的商品')
    router.push('/cart')
  }
  
  // 模拟获取默认地址
  // 在实际项目中，这里应该从API获取用户的收货地址
  selectedAddress.value = {
    name: '张三',
    phone: '13800138000',
    province: '北京市',
    city: '北京市',
    district: '海淀区',
    detailAddress: '北京大学 1号公寓 301室',
    isDefault: true
  }
})

// 计算总价
const subtotal = computed(() => {
  return checkoutItems.value.reduce((total, item) => total + item.price * item.quantity, 0)
})

// 运费（模拟数据，实际应该根据地址和商品重量计算）
const shippingFee = computed(() => subtotal.value >= 99 ? 0 : 10)

// 实付金额
const totalAmount = computed(() => subtotal.value + shippingFee.value)

const saveAddress = async () => {
  await addressFormRef.value.validate()
  
  // 构建地址对象
  const newAddress = {
    ...addressForm,
    province: addressForm.region[0] || '',
    city: addressForm.region[1] || '',
    district: addressForm.region[2] || ''
  }
  
  // 保存地址
  selectedAddress.value = newAddress
  showAddressDialog.value = false
  ElMessage.success('地址保存成功')
}

const submitOrder = async () => {
  if (!selectedAddress.value) {
    ElMessage.warning('请选择收货地址')
    return
  }
  
  isSubmitting.value = true
  
  try {
    // 构建订单数据
    const orderData = {
      items: checkoutItems.value,
      address: selectedAddress.value,
      paymentMethod,
      remark,
      subtotal: subtotal.value,
      shippingFee: shippingFee.value,
      totalAmount: totalAmount.value
    }
    
    // 创建订单
    const orderId = await orderStore.createOrder(orderData)
    
    // 从购物车中移除已下单的商品
    checkoutItems.value.forEach(item => {
      cartStore.removeFromCart(item.id)
    })
    
    // 清空sessionStorage中的结算商品
    sessionStorage.removeItem('checkoutItems')
    
    ElMessage.success('订单创建成功！')
    
    // 跳转到支付页面或订单详情页面
    router.push(`/order/detail/${orderId}`)
  } catch (error) {
    ElMessage.error('订单创建失败，请稍后重试')
    console.error('创建订单失败:', error)
  } finally {
    isSubmitting.value = false
  }
}
</script>

<style scoped>
.order-confirm-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h2 {
  font-size: 24px;
  color: #333;
}

.section {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.address-card {
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.address-card:hover {
  border-color: #409eff;
}

.address-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 10px;
}

.name {
  font-weight: bold;
  color: #333;
}

.phone {
  color: #666;
}

.address-detail {
  color: #666;
  line-height: 1.5;
}

.empty-address {
  padding: 40px 0;
  cursor: pointer;
}

.empty-address .el-icon {
  font-size: 60px;
  color: #e0e0e0;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 15px;
}

.product-details {
  flex: 1;
}

.product-title {
  font-size: 14px;
  margin-bottom: 5px;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-category {
  font-size: 12px;
  color: #999;
}

.price,
.subtotal {
  color: #ff4d4f;
  font-weight: bold;
}

.order-form {
  padding: 10px 0;
}

.payment-summary {
  background: #fafafa;
  padding: 20px;
  border-radius: 4px;
  margin-top: 30px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 16px;
}

.summary-item.total {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e0e0e0;
  font-size: 18px;
}

.total-price {
  font-size: 24px;
  font-weight: bold;
  color: #ff4d4f;
}

.submit-btn {
  margin-top: 20px;
  text-align: right;
}

@media (max-width: 768px) {
  .address-header {
    flex-wrap: wrap;
  }
  
  .product-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .product-image {
    margin-right: 0;
  }
  
  .summary-item {
    font-size: 14px;
  }
  
  .total-price {
    font-size: 20px;
  }
}
</style>